from common.CommonNode import CommonNode


class CommonHeap:
    def __init__(self):
        pass

    @staticmethod
    def firstFit(node, size, newNode):
        p = node
        addChunk = False
        while p is not None:
            if p.getSize() > size:
                break
            p = p.getNext()
        if p is not None:
            if p.getSize() > size:
                addChunk = True
                splitNode = newNode(p.getSize() - size, p.getStart() + size, None)
                splitNode.setPre(p)
                p.setSize(size)
                p.setNext(splitNode)
        return p, addChunk

    @staticmethod
    def freeObject(node):
        node.setObj(None)
        decChunk = 0
        if node.getPre() is not None and node.getPre().isFree():
            preEnd = node.getPre().getSize() + node.getPre().getStart()
            if preEnd == node.start:
                decChunk += 1
                node = CommonNode.merge(node.getPre(), node)
        if node.getNext() is not None and node.getNext().isFree():
            end = node.getSize() + node.getStart()
            if end == node.getNext().getStart():
                decChunk += 1
                CommonNode.merge(node, node.getNext())
        return decChunk

    @staticmethod
    def markNode(node):
        node.mark()
        CommonHeap.mark(node.getChildren())

    @staticmethod
    def mark(nodes):
        for node in nodes:
            if not node.isMarked():
                CommonHeap.markNode(node)

